<template>
  <div class="bg-white rounded-lg shadow-md p-6 mb-6">
    <!-- 文档上传区域 -->
    <div class="mb-8">
      <h2 class="text-xl font-semibold mb-4 flex items-center">
        <UploadIcon class="w-5 h-5 mr-2 text-blue-600" />
        上传文档到知识库
      </h2>
      <div class="border-2 border-dashed border-gray-300 rounded-lg p-8 text-center hover:border-blue-500 transition-colors duration-300">
        <label class="cursor-pointer">
          <input type="file" class="hidden" @change="handleFileSelected" accept=".pdf,.docx,.txt,.md" multiple />
          <div class="space-y-2">
            <CloudUploadIcon class="w-12 h-12 mx-auto text-gray-400" />
            <p class="text-gray-600">拖放文件到此处，或<span class="text-blue-600 font-medium">浏览文件</span></p>
            <p class="text-xs text-gray-400">支持 PDF, DOCX, TXT, MD 格式，单个文件不超过 20MB</p>
          </div>
        </label>
      </div>

      <!-- 上传队列 -->
      <div v-if="uploadQueue.length > 0" class="mt-4 space-y-2">
        <div v-for="(file, index) in uploadQueue" :key="index" class="flex items-center p-3 bg-gray-50 rounded-md">
          <div class="flex-1 min-w-0">
            <p class="text-sm font-medium text-gray-900 truncate">{{ file.name }}</p>
            <div class="w-full bg-gray-200 rounded-full h-1.5 mt-1">
              <div
                class="bg-blue-600 h-1.5 rounded-full"
                :style="{ width: file.progress + '%' }"
              ></div>
            </div>
          </div>
          <div class="ml-4 flex-shrink-0">
            <button
              v-if="!file.uploading"
              class="text-gray-400 hover:text-red-500"
              @click="removeFromQueue(index)"
            >
              <XIcon class="w-4 h-4" />
            </button>
            <span v-else class="text-xs text-gray-500">{{ file.progress }}%</span>
          </div>
        </div>
        <button
          class="w-full bg-blue-600 text-white py-2 px-4 rounded-md hover:bg-blue-700 transition-colors duration-300"
          @click="uploadFiles"
          :disabled="isUploading || uploadQueue.length === 0"
        >
          <UploadIcon class="w-4 h-4 mr-2 inline" v-if="!isUploading" />
          <Loader2Icon class="w-4 h-4 mr-2 inline animate-spin" v-if="isUploading" />
          {{ isUploading ? '正在上传...' : '开始上传' }}
        </button>
      </div>
    </div>

    <!-- 文档列表区域 -->
    <div>
      <h2 class="text-xl font-semibold mb-4 flex items-center">
        <FileTextIcon class="w-5 h-5 mr-2 text-blue-600" />
        已上传文档
      </h2>
      <div class="overflow-x-auto">
        <table class="min-w-full divide-y divide-gray-200">
          <thead class="bg-gray-50">
            <tr>
              <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">文档名称</th>
              <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">上传时间</th>
              <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">页数</th>
              <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">状态</th>
              <th scope="col" class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">操作</th>
            </tr>
          </thead>
          <tbody class="bg-white divide-y divide-gray-200">
            <tr v-if="documents.length === 0 && !isLoadingDocuments">
              <td colspan="5" class="px-6 py-10 text-center text-gray-500">
                暂无上传的文档
              </td>
            </tr>
            <tr v-if="isLoadingDocuments">
              <td colspan="5" class="px-6 py-10 text-center">
                <Loader2Icon class="w-8 h-8 mx-auto text-gray-400 animate-spin" />
              </td>
            </tr>
            <tr v-for="doc in documents" :key="doc.document_id" class="hover:bg-gray-50 transition-colors duration-150">
              <td class="px-6 py-4 whitespace-nowrap">
                <div class="flex items-center">
                  <FileIcon class="w-5 h-5 text-gray-400 mr-3" />
                  <div class="text-sm font-medium text-gray-900 truncate max-w-xs">
                    {{ doc.filename }}
                  </div>
                </div>
              </td>
              <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                {{ formatDate(doc.upload_time) }}
              </td>
              <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                {{ doc.page_count }}
              </td>
              <td class="px-6 py-4 whitespace-nowrap">
                <span
                  class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full"
                  :class="getStatusClass(doc.status)"
                >
                  {{ getStatusText(doc.status) }}
                </span>
              </td>
              <td class="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
                <button
                  class="text-red-600 hover:text-red-900 mr-4"
                  @click="deleteDocument(doc.document_id, doc.filename)"
                >
                  删除
                </button>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive } from 'vue';
import { UploadIcon, XIcon, FileTextIcon, FileIcon, Loader2Icon, CloudUploadIcon } from 'lucide-vue-next';

// 定义文档类型接口
interface Document {
  document_id: string;
  filename: string;
  upload_time: string;
  page_count: number;
  status: string;
}

// 定义上传文件类型接口
interface UploadFile {
  file: File;
  name: string;
  progress: number;
  uploading: boolean;
}

// 状态管理
const documents = ref<Document[]>([]);
const isLoadingDocuments = ref<boolean>(false);
const uploadQueue = ref<UploadFile[]>([]);
const isUploading = ref<boolean>(false);

// 生命周期钩子：组件挂载时获取文档列表
onMounted(() => {
  fetchDocuments();
});

// 获取文档列表
const fetchDocuments = async () => {
  isLoadingDocuments.value = true;
  try {
    const response = await fetch('http://localhost:8000/documents');
    if (!response.ok) throw new Error('获取文档列表失败');
    const data = await response.json();
    documents.value = data;
  } catch (error) {
    console.error('获取文档列表错误:', error);
    alert('获取文档列表失败，请重试');
  } finally {
    isLoadingDocuments.value = false;
  }
};

// 处理文件选择
const handleFileSelected = (e: Event) => {
  const input = e.target as HTMLInputElement;
  if (!input.files) return;

  Array.from(input.files).forEach(file => {
    // 验证文件类型
    const allowedTypes = ['.pdf', '.docx', '.txt', '.md'];
    const fileExtension = file.name.split('.').pop()?.toLowerCase() || '';
    const hasValidExtension = allowedTypes.some(type => type.includes(fileExtension));

    if (!hasValidExtension) {
      alert(`不支持的文件类型: ${file.name}。仅支持 PDF, DOCX, TXT, MD 格式。`);
      return;
    }

    // 验证文件大小 (20MB)
    if (file.size > 20 * 1024 * 1024) {
      alert(`文件过大: ${file.name}。单个文件不能超过 20MB。`);
      return;
    }

    // 添加到上传队列
    uploadQueue.value.push({
      file,
      name: file.name,
      progress: 0,
      uploading: false
    });
  });

  // 清空input值，允许重复选择同一文件
  input.value = '';
};

// 从队列中移除文件
const removeFromQueue = (index: number) => {
  uploadQueue.value.splice(index, 1);
};

// 上传文件
const uploadFiles = async () => {
  if (uploadQueue.value.length === 0) return;

  isUploading.value = true;

  // 创建FormData并上传每个文件
  for (const fileItem of uploadQueue.value) {
    fileItem.uploading = true;

    const formData = new FormData();
    formData.append('file', fileItem.file);

    try {
      const response = await fetch('http://localhost:8000/upload', {
        method: 'POST',
        body: formData,
        // 上传进度处理
        onUploadProgress: (progressEvent) => {
          if (progressEvent.lengthComputable) {
            const percent = Math.round((progressEvent.loaded * 100) / progressEvent.total);
            fileItem.progress = percent;
          }
        }
      });

      if (!response.ok) throw new Error('上传失败');

      // 上传成功后重新获取文档列表
      await fetchDocuments();
    } catch (error) {
      console.error('文件上传错误:', error);
      alert(`文件 ${fileItem.name} 上传失败，请重试`);
    } finally {
      fileItem.uploading = false;
    }
  }

  // 清空上传队列
  uploadQueue.value = [];
  isUploading.value = false;
};

// 删除文档
const deleteDocument = async (documentId: string, fileName: string) => {
  if (!confirm(`确定要删除文档 ${fileName}？此操作不可恢复。`)) return;
  try {
    const response = await fetch(`http://localhost:8000/documents/${documentId}`, {
      method: 'DELETE'
    });
    if (!response.ok) throw new Error('删除文档失败');
    // 删除成功后重新获取文档列表
    await fetchDocuments();
  } catch (error) {
    console.error('删除文档错误:', error);
    alert(`删除文档 ${fileName} 失败，请重试`);
  }
}

// 格式化日期
const formatDate = (dateString: string) => {
  const date = new Date(dateString);
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  });
};

// 获取状态样式
const getStatusClass = (status: string) => {
  switch (status) {
    case 'processed':
      return 'bg-green-100 text-green-800';
    case 'processing':
      return 'bg-yellow-100 text-yellow-800';
    case 'failed':
      return 'bg-red-100 text-red-800';
    default:
      return 'bg-gray-100 text-gray-800';
  }
};

// 获取状态文本
const getStatusText = (status: string) => {
  switch (status) {
    case 'processed':
      return '已处理';
    case 'processing':
      return '处理中';
    case 'failed':
      return '处理失败';
    default:
      return status;
  }
};

</script>